# -*- coding: utf-8 -*-
# @Time    : 2021/10/26 16:03
# @Author  : huangwei
# @File    : img2excel.py
# @Software: PyCharm
import cv2
from config_args import args
from text import TextDetector, TextRecognizer
from method import get_lines, get_text_boxes, dist
from table_line_net import table_net

# 动态分配内存
import tensorflow as tf

config = tf.compat.v1.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.5
config.gpu_options.allow_growth = True
session = tf.compat.v1.InteractiveSession(config=config)

# 检测文本框和识别文字方法
text_detector = TextDetector(args)
text_recognizer = TextRecognizer(args)

# 加载识别表格线的模型
table_line_model_path = 'det_table_line_models/table-line.h5'
table_line_model = table_net((None, None, 3), 2)
table_line_model.load_weights(table_line_model_path)


def get_intersect_point( line1, line2 ):
    # 求两条线段的交点
    x1, y1, x2, y2 = line1
    x3, y3, x4, y4 = line2

    px = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / (
            (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))
    py = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / (
            (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))

    return px, py


def is_intersect( line1, line2 ):
    x1, y1, x2, y2 = line1
    x3, y3, x4, y4 = line2

    # 3，4是否在12两侧
    x12 = x2 - x1
    y12 = y2 - y1
    x13 = x3 - x1
    y13 = y3 - y1
    x14 = x4 - x1
    y14 = y4 - y1
    d1 = x12 * y13 - x13 * y12
    d2 = x12 * y14 - x14 * y12
    delta1 = d1 * d2

    # 1，2是否在34两侧
    x34 = x4 - x3
    y34 = y4 - y3
    x31 = x1 - x3
    y31 = y1 - y3
    x32 = x2 - x3
    y32 = y2 - y3
    d3 = x34 * y31 - x31 * y34
    d4 = x34 * y32 - x32 * y34
    delta2 = d3 * d4

    if delta1 <= 0 and delta2 <= 0:
        return True
    else:
        return False


def get_intersect_index( line, lines_list ):
    line_num = len(lines_list)
    cross_list = []

    for j in range(line_num):
        # 判断两条线段是否相交
        is_inter = is_intersect(line, lines_list[j])
        if is_inter:
            cross_list.append(j)

    return cross_list


def fit_lines( lines1, lines2, axis=0 ):
    new_lines = []
    for line1 in lines1:
        cross_list = get_intersect_index(line1, lines2)
        # 求第一个和最后一个相交的交点
        temp_line1 = lines2[cross_list[0]]
        temp_line2 = lines2[cross_list[-1]]

        # 求两条线段的交点
        cx1, cy1 = get_intersect_point(line1, temp_line1)
        cx2, cy2 = get_intersect_point(line1, temp_line2)
        x1, y1, x2, y2 = line1

        # 如果有条线为边界线，则直接去除突出的部分
        if cross_list[0] == 0:
            if axis == 0:
                x1, y1 = cx1 - 1, cy1
            else:
                x1, y1 = cx1, cy1 - 1
        else:
            # 如果突出超过一半且没有文字框，则连接起来
            dis1 = dist((x1, y1), (cx1, cy1))
            # 上一条线和这条线的距离
            temp_line3 = lines2[cross_list[0] - 1]
            tx1, ty1, tx2, ty2 = temp_line1
            tx3, ty3, tx4, ty4 = temp_line3
            if axis == 0:
                # 横线求x之间的距离
                tcx1 = (tx1 + tx2) / 2
                tcx2 = (tx3 + tx4) / 2
                det_dis = tcx1 - tcx2
            else:
                # 竖线求y之间的距离
                tcy1 = (ty1 + ty2) / 2
                tcy2 = (ty3 + ty4) / 2
                det_dis = tcy1 - tcy2

            print("det dis:", det_dis, cross_list[0], temp_line1, line1)
            if dis1 > det_dis / 3:
                print("dis:", dis1)
            pass

        if cross_list[-1] == (len(lines2) - 1):
            if axis == 0:
                x2, y2 = cx2 + 1, cy2
            else:
                x2, y2 = cx2, cy2 + 1
        else:
            pass

        line1 = [x1, y1, x2, y2]
        new_lines.append(line1)
    return new_lines


if __name__ == '__main__':
    file_path = "images/simple3.png"
    img = cv2.imread(file_path)

    # 找到所有的横线和竖线
    input_size = (1024, 1024)
    rows_lines, cols_lines = get_lines(file_path, table_line_model, input_size)
    # print(len(rows_lines), len(cols_lines))

    det_text_boxes = get_text_boxes(img, text_detector, rows_lines)
    print("文本框的数量为：", len(det_text_boxes))

    row_lines = fit_lines(rows_lines, cols_lines)

    # 依次扫描每一条横线和竖线，判断其是否需要去除冒头的部分或延长冒头的部分。
